﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ThresholdAssistant.DataContract.Result;
using ThresholdAssistant.WebAPI.Models;
using ThresholdAssistant.WebAPI.Models.Constants;
using ThresholdAssistant.WebAPI.Repository;

namespace ThresholdAssistant.WebAPI.Controllers
{
    /// <summary>
    /// 多媒体控制器
    /// </summary>
    [Route("api/media")]
    public class MediaController : BaseController
    {
        public MemberRepository MemberRepository { get; set; }

        /// <summary>
        /// 多媒体上传
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        [HttpPost("upload-pic")]
        [AllowAnonymous]
        public async Task<ContractResult<string>> UploadPicAsync([FromForm] UploadPicParam param, IFormFile file)
        {
            var result = new ContractResult<string>();
            FileInfo fileInfo = new FileInfo(file?.FileName);
            //var list = new[] { ".jpg", ".jpeg", ".png" };
            //if (!list.Contains(fileInfo.Extension.ToLower()))
            //{
            //    return result.SetError(ErrorResultEnum.FileExtendNoSupport);
            //}
            //var imgTypeList = new[] { 0, 1, 2, 3 };
            //if (!imgTypeList.Contains(param.Type.GetHashCode()))
            //{
            //    return result.SetError(ErrorResultEnum.TypeNoSupport);
            //}
            string fileName = Guid.NewGuid().ToString("N") + fileInfo.Extension;
            var path = AppSettingConstant.ImgSavePath;
            var directory = $"/upfile";//上传文件存放的服务器目录
            var newpath = $"{path}{directory}";
            if (!Directory.Exists(newpath))
            {
                Directory.CreateDirectory(newpath);//目录不存在创建
            }
            var filepath = $"{newpath}/{fileName}";
            using (var fs = new FileStream(filepath, FileMode.Create, FileAccess.Write))
            {
                await file.CopyToAsync(fs);
            }

            //var result = await UploadQiniuAsync(filepath, fileName);
            //if (result.Code == 200 && result.RefCode == 200)
            //{
            //    var resultTextJson = JsonConvert.DeserializeObject<TextParam>(result.Text);
            //    url = $"{ConfigHelper.GetValue("ApiConfig:QiniuCdnUrl")}/{resultTextJson.Url}";
            //    var _fileInfo = new FileInfo(filepath);
            //    _fileInfo.Delete();
            //}
            var url = $"{AppSettingConstant.HostImgUrl}{directory}/{fileName}";
            await MemberRepository.UpdateProfileAsync(param.MemberId, url);
            result.Data = url;
            return result.SetSuceccful();
        }



        ///// <summary>
        ///// 删除图片
        ///// </summary>
        ///// <returns></returns>
        //[HttpPost("delete-img")]
        //public async Task<ContractResult> DeleteImgAsync(DeleteImgParam param)
        //{
        //    var result = new ContractResult();
        //    if (param.DelToken != AppSettingConstant.DelImgUrlToken)
        //    {
        //        return result.SetError(ErrorResultEnum.DelImgUrlTokenError);
        //    }
        //    var imgInfo = await ActivityImgRepository.GetInfoByImgUrlAsync(param.ImgUrl);
        //    if (imgInfo == null)
        //    {
        //        return result.SetError(ErrorResultEnum.FileNotExists);
        //    }
        //    var path = AppSettingConstant.ImgSavePath;
        //    var filePath = $"{AppSettingConstant.ImgSavePath}{param.ImgUrl.Replace(AppSettingConstant.HostImgUrl, "")}";
        //    FileInfo fileInfo = new FileInfo(filePath);
        //    fileInfo.Delete();

        //    await ActivityImgRepository.DeleteAsync(imgInfo.Id);
        //    return result.SetSuceccful();
        //}

    }
}
